<?php

class ItemType extends Eloquent implements CrudableInterface
{
    public function itemCategory() {
        return $this->belongsTo('ItemCategory');
    }

    public function group() {
        return $this->belongsTo('Group');
    }

    public function lots() {
        return $this->hasMany('Lot');
    }

    public static function indexColumns()
    {
        return array (
            'ID' => array (
                'type'=>'numeric',
                'field'=>'id'
            ),
            'Name' => array (
                'type'=>'string',
                'field'=>'name'
            ),
            'Category' => array (
                'type'=>'string',
                'field'=>function ($obj) { return $obj->itemCategory ? $obj->itemCategory->name : ''; }
            ),                
            'Pounds in Stock' => array (
                'type'=>'numeric',
                'field'=>function ($obj) { 
                    $total = 0;
                    foreach ($obj->lots as $lot) {
                        $total += $lot->items()->where('status', '=', 'in stock')->count() * $lot->pounds_per_item;
                    }
                    return $total;
                }
            ),
        );
    }

    public function showTitle() 
    {
        return $this->name;
    }

    public function showFields()
    {
        return array (
            'ID' => $this->id,
            'Name' => $this->name,
            'Category' => $this->itemCategory ? $this->itemCategory->name : 'unknown'
        );
    }

    public static function editFields($obj=null)
    {
       $item_categories = ItemCategory::whereHas('group', function($q) {
                $q->where('group_id', '=', Auth::user()->group_id);
            })->get()->lists('name', 'id');

        return array (
            'name' => array (
                'type'=>'text',
                'label'=>'Name',
            ),
            'item_category_id' => array (
                'type'=>'select',
                'options'=>$item_categories,
                'label'=>'Category',
                'value'=> ($obj && $obj->itemCategory) ? $obj->itemCategory->id : '',
            ),                
            
        );
        
    }
}